// 添加请求超时处理
const TIMEOUT = 30000; // 30秒超时

async function timeoutPromise(promise) {
    let timeoutId;
    const timeoutPromise = new Promise((_, reject) => {
        timeoutId = setTimeout(() => {
            reject(new Error('请求超时'));
        }, TIMEOUT);
    });

    try {
        const result = await Promise.race([promise, timeoutPromise]);
        clearTimeout(timeoutId);
        return result;
    } catch (error) {
        clearTimeout(timeoutId);
        throw error;
    }
}

class HttpClient {
    static async request(url, method, data = null) {
        const fullUrl = url.startsWith('http') ? url : CONFIG.BASE_URL + url;
        
        const options = {
            method: method,
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json',
                'Access-Control-Allow-Origin': '*',
                'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
                'Access-Control-Allow-Headers': 'Content-Type, Authorization'
            },
            credentials: 'include',
            mode: 'cors'
        };

        if (data) {
            options.body = JSON.stringify(data);
        }

        try {
            const response = await timeoutPromise(fetch(fullUrl, options));
            if (!response.ok) {
                throw new Error('请求失败: ' + response.statusText);
            }
            
            const text = await response.text(); // 先获取文本
            if (!text) {
                return {}; // 如果响应为空，返回空对象
            }
            
            try {
                return JSON.parse(text); // 尝试解析JSON
            } catch (e) {
                console.log('Response text:', text); // 打印原始响应
                return {}; // JSON解析失败时返回空对象
            }
        } catch (error) {
            console.error('请求错误:', error);
            throw error;
        }
    }

    static get(url) {
        return this.request(url, 'GET');
    }

    static post(url, data) {
        return this.request(url, 'POST', data);
    }
} 